<template>
  <page-view class="page-view" :title="false">
    <div slot="headerContent">
      <a-breadcrumb class="s-breadcrumb">
        <a-breadcrumb-item><nuxt-link to="/meal/manage">餐券管理</nuxt-link></a-breadcrumb-item>
        <a-breadcrumb-item><nuxt-link to="/meal/date">订餐日期设置</nuxt-link></a-breadcrumb-item>
        <a-breadcrumb-item>批量设置</a-breadcrumb-item>
      </a-breadcrumb>
    </div>

    <a-card class="s-card">
      <a-spin :spinning="sending">

        <a-table
          bordered
          class="s-table"
          :columns="columns"
          :data-source="dateData"
          :scroll="{ y: scrollY }"
          row-key="date"
          :pagination="false"
        >
          <span slot="breakfast" slot-scope="_, record" @change="onChange($event, record, '早餐')">
            <a-checkbox :checked="$get(record, 'typeNames', '').includes('早餐')" />
          </span>
          <span slot="lunch" slot-scope="_, record" @change="onChange($event, record, '午餐')">
            <a-checkbox :checked="$get(record, 'typeNames', '').includes('午餐')" />
          </span>
          <span slot="dinner" slot-scope="_, record" @change="onChange($event, record, '晚餐')">
            <a-checkbox :checked="$get(record, 'typeNames', '').includes('晚餐')" />
          </span>
        </a-table>

        <div class="tips">注：不勾选就餐时间，当天该时间段不可订</div>

        <div class="footer-btn">
          <a-button type="primary" @click="setDate">确定</a-button>
          <a-button @click="goback">取消</a-button>
        </div>

      </a-spin>
    </a-card>

  </page-view>
</template>

<script>
import { mapState, mapActions } from 'vuex'
import { uuid, requestList } from '@/utils/util'
import { PageView } from '@/components'

export default {
  name: 'Edit',
  components: { PageView },
  props: {
    dateStr: {
      type: String,
      default: ''
    }
  },

  async asyncData ({ store, route }) {
    const data = {
      dateData: []
    }
    const { $moment, $get } = store
    const { mealTypeNames } = store.getters.meal
    const dateArr = route.params.dateStr.split(',')
    dateArr.sort((a, b) => {
      return $moment(a || '9999-12-31').isBefore(b || '9999-12-31') ? -1 : 1
    })
    const params = {}
    if (dateArr.length > 1) {
      const timeArr = dateArr.map(i => new Date(i).getTime())
      params.minScheduleDate = $moment(Math.min(...timeArr)).format('YYYY-MM-DD')
      params.maxScheduleDate = $moment(Math.max(...timeArr)).format('YYYY-MM-DD')
    } else {
      params.scheduleDate = $moment(dateArr[0] || '').format('YYYY-MM-DD')
    }
    if (!$get(mealTypeNames, 'length')) await store.dispatch('meal/getMealType')
    await store.dispatch('meal/getSchedule', params)

    const allNames = mealTypeNames.join(',')
    const { scheduleMaps } = store.getters.meal
    const { dateData } = data
    dateArr.forEach(date => {
      const typeNames = $get(scheduleMaps[date], 'typeNames', allNames).split(',')
      dateData.push({ date, typeNames })
    })
    return data
  },

  data () {
    return {
      scrollY: 600,
      sending: false,
      block: false,

      dateData: [],
      columns: [
        { title: '订餐日期', align: 'center', dataIndex: 'date' },
        { title: '早餐', width: '25%', key: uuid(), align: 'center', scopedSlots: { customRender: 'breakfast' }},
        { title: '午餐', width: '25%', key: uuid(), align: 'center', scopedSlots: { customRender: 'lunch' }},
        { title: '晚餐', width: '25%', key: uuid(), align: 'center', scopedSlots: { customRender: 'dinner' }}
      ]
    }
  },

  computed: {
    ...mapState({
      meal: state => state.meal,
      mealTypeMaps: state => state.meal.mealTypeMaps,
      scheduleMaps: state => state.meal.scheduleMaps
    })
  },

  watch: {
    dateStr: {
      handler (date) {
        if (!this.dateData.length) this.dateData.push({ date, typeNames: ['早餐', '午餐', '晚餐'] })
      },
      immediate: true
    }

  },

  mounted () {
    if (!process.client) return false
    const viewHeight = document.querySelector('.ant-layout-content').offsetHeight
    this.scrollY = viewHeight - 64 - 55 - 24 - 48 - 55 - 22 - 32
    if (this.scrollY < 0) this.scrollY = 600
  },

  methods: {
    ...mapActions('meal', ['addSchedule', 'delSchedule', 'getSchedule']),

    onChange (e, item, name) {
      const { scheduleMaps, $get } = this
      if (!item.typeNames) Object.assign(item, { typeNames: [] })
      const { typeNames, date } = item
      const index = typeNames.indexOf(name)
      const old = scheduleMaps[date] || {}
      const oldName = $get(old, 'typeNames', '').split(',').filter(i => i)
      const oldIndex = oldName.indexOf(name)
      if (oldIndex > -1) {
        this.$message.destroy()
        this.$message.error('请前往新建换餐通知处删除')
      } else {
        if (index > -1) typeNames.splice(index, 1)
        else typeNames.push(name)
      }
    },

    async setDate () {
      if (this.sending) return false
      const { dateData, scheduleMaps = new Map(), $difference, $get, getDelData, getAddData, delCallBack, addCallBack, delSchedule, addSchedule, afterRequest } = this
      const delArr = []
      const addArr = []
      dateData.forEach(item => {
        const { date, typeNames } = item
        const old = scheduleMaps[date] || {}
        const oldName = $get(old, 'typeNames', '').split(',')
        const addNames = $difference(typeNames, oldName).filter(i => i)
        const delNames = $difference(oldName, typeNames).filter(i => i)
        if (addNames.length) addArr.push(...getAddData(date, addNames))
        if (delNames.length) delArr.push(...getDelData(old, delNames))
      })

      const requests = []
      delArr.map(({ scheduleDate, id }) => requests.push({ fn: delSchedule, params: id, cb: res => delCallBack({ res, scheduleDate, id }) }))
      if (addArr.length) requests.push({ fn: addSchedule, params: addArr, cb: res => addCallBack(res, addArr) })

      if (requests.length) {
        this.block = false
        this.sending = true
        await requestList(requests)
      }

      afterRequest()
    },

    afterRequest () {
      const { block, getSchedule, goback, $message } = this
      if (!block) {
        if (this.sending) {
          $message.success('已修改')
          getSchedule()
        }
        goback()
      }
    },

    addCallBack (res, addList) {
      const { data } = res
      const { $get, $message } = this
      if ($get(data, 'code') !== '000000') {
        $message.error($get(data, 'mesg', '请稍后再试'))
        this.block = true
      }
    },

    delCallBack ({ res, scheduleDate, id }) {
      const { data } = res
      const { $get } = this
      if ($get(data, 'code') !== '000000') {
        this.$message.error($get(data, 'mesg', '请稍后再试'))
        this.block = true
      }
    },

    getDelData ({ ids = '', typeNames = '', scheduleDate }, names) {
      const delIds = names.map(name => {
        const index = typeNames.indexOf(names)
        return { scheduleDate, id: ids.split(',')[index] }
      })
      return delIds
    },

    getAddData (scheduleDate, names) {
      const { mealTypeMaps } = this
      const arr = names.map(name => {
        const { price, endTime, startTime, id } = mealTypeMaps.get(name)
        return { scheduleDate, price, endTime, startTime, typeId: id, name }
      })
      return arr
    },

    goback () {
      this.$router.go(-1)
    }
  }
}
</script>

<style lang="less" scoped>
  .s-card {
    .tips {
      color:@red;
    }

    .footer-btn {
      .Flex;
      justify-content: center;

      .ant-btn {
        margin-right: 50px;
      }
    }
  }

</style>
